/**
 * 主界面逻辑
 */

// 全局状态
let projects = [];
let currentProject = null;
let isLoading = false;

// DOM 元素
let elements = {};

/**
 * 初始化应用
 */
async function initApp() {
  console.log('[Main] 初始化应用');
  
  // 等待API客户端初始化
  const apiReady = await waitForApi();
  if (!apiReady) {
    console.error('[Main] API客户端初始化失败');
    showToast('系统错误：无法初始化API客户端', 'error');
    return;
  }
  
  console.log('[Main] API客户端已准备就绪');
  
  // 获取DOM元素
  initElements();
  
  // 绑定事件
  bindEvents();
  
  // 加载初始数据
  await loadProjects();
  
  // 启动定时刷新
  startAutoRefresh();
  
  console.log('[Main] 应用初始化完成');
}

/**
 * 初始化DOM元素
 */
function initElements() {
  elements = {
    // 主要容器
    projectsList: document.getElementById('projectsList'),
    projectsGrid: document.getElementById('projectsGrid'),
    loadingState: document.getElementById('loadingState'),
    emptyState: document.getElementById('emptyState'),
    
    // 统计信息
    totalProjects: document.getElementById('totalProjects'),
    activeProjects: document.getElementById('activeProjects'),
    
    // 按钮
    addProjectBtn: document.getElementById('addProjectBtn'),
    refreshBtn: document.getElementById('refreshBtn'),
    deactivateAllBtn: document.getElementById('deactivateAllBtn'),
    viewRulesBtn: document.getElementById('viewRulesBtn'),
    
    // 表单
    addProjectForm: document.getElementById('addProjectForm'),
    projectNameInput: document.getElementById('projectName'),
    confirmAddProject: document.getElementById('confirmAddProject'),
    
    renameProjectForm: document.getElementById('renameProjectForm'),
    newProjectNameInput: document.getElementById('newProjectName'),
    confirmRenameProject: document.getElementById('confirmRenameProject'),
    
    deleteProjectName: document.getElementById('deleteProjectName'),
    confirmDeleteProject: document.getElementById('confirmDeleteProject'),
    
    // 其他
    sortSelect: document.getElementById('sortSelect'),
    rulesContainer: document.getElementById('rulesContainer'),
  };
}

/**
 * 绑定事件
 */
function bindEvents() {
  // 添加项目
  elements.addProjectBtn.addEventListener('click', () => showModal('addProjectModal'));
  elements.confirmAddProject.addEventListener('click', handleAddProject);
  elements.addProjectForm.addEventListener('submit', (e) => {
    e.preventDefault();
    handleAddProject();
  });
  
  // 重命名项目
  elements.confirmRenameProject.addEventListener('click', handleRenameProject);
  elements.renameProjectForm.addEventListener('submit', (e) => {
    e.preventDefault();
    handleRenameProject();
  });
  
  // 删除项目
  elements.confirmDeleteProject.addEventListener('click', handleDeleteProject);
  
  // 刷新和操作
  elements.refreshBtn.addEventListener('click', handleRefresh);
  elements.deactivateAllBtn.addEventListener('click', handleDeactivateAll);
  elements.viewRulesBtn.addEventListener('click', handleViewRules);
  
  // 排序
  elements.sortSelect.addEventListener('change', handleSort);
  
  // 键盘快捷键
  document.addEventListener('keydown', handleKeyboard);
  
  // 模态框点击外部关闭
  document.addEventListener('click', (e) => {
    if (e.target.classList.contains('modal')) {
      const modalId = e.target.id;
      closeModal(modalId);
    }
  });
}

/**
 * 加载项目列表
 */
async function loadProjects() {
  if (isLoading) return;
  
  // 检查API客户端是否已初始化
  if (!checkApiReady()) {
    console.error('[Main] API客户端未初始化');
    return;
  }
  
  isLoading = true;
  showLoadingState();
  
  try {
    console.log('[Main] 开始加载项目列表');
    console.log('[Main] API客户端状态:', window.api);
    
    const response = await api.getProjects();
    console.log('[Main] API响应:', response);
    
    if (response.success) {
      projects = response.data || [];
      console.log('[Main] 项目数据:', projects);
      projects.forEach(project => {
        console.log(`[Main] 项目 ${project.name} 激活环境:`, project.activeEnvironment);
      });
      renderProjects();
      updateStats();
    } else {
      throw new Error(response.error || '加载项目失败');
    }
  } catch (error) {
    console.error('[Main] 加载项目失败:', error);
    console.error('[Main] 错误详情:', error.stack);
    showToast('加载项目失败: ' + error.message, 'error');
    showEmptyState();
  } finally {
    isLoading = false;
  }
}

/**
 * 渲染项目列表
 */
function renderProjects() {
  console.log(`[Main] 渲染 ${projects.length} 个项目`);
  
  if (projects.length === 0) {
    showEmptyState();
    return;
  }
  
  // 排序项目
  const sortedProjects = sortProjects(projects);
  
  // 生成HTML
  const html = sortedProjects.map(createProjectCard).join('');
  
  // 更新DOM
  elements.projectsGrid.innerHTML = html;
  showProjectsGrid();
}

/**
 * 排序项目
 */
function sortProjects(projectList) {
  const sortBy = elements.sortSelect.value;
  const sorted = [...projectList];
  
  switch (sortBy) {
    case 'name':
      sorted.sort((a, b) => a.name.localeCompare(b.name));
      break;
    case 'updated':
      sorted.sort((a, b) => new Date(b.updatedAt || 0) - new Date(a.updatedAt || 0));
      break;
    case 'status':
      sorted.sort((a, b) => {
        const aActive = a.activeEnvironment ? 1 : 0;
        const bActive = b.activeEnvironment ? 1 : 0;
        return bActive - aActive;
      });
      break;
  }
  
  return sorted;
}

/**
 * 更新统计信息
 */
function updateStats() {
  const activeCount = projects.filter(p => p.activeEnvironment).length;
  
  elements.totalProjects.textContent = projects.length;
  elements.activeProjects.textContent = activeCount;
}



/**
 * 显示状态
 */
function showLoadingState() {
  elements.loadingState.style.display = 'flex';
  elements.emptyState.style.display = 'none';
  elements.projectsGrid.style.display = 'none';
}

function showEmptyState() {
  elements.loadingState.style.display = 'none';
  elements.emptyState.style.display = 'flex';
  elements.projectsGrid.style.display = 'none';
}

function showProjectsGrid() {
  elements.loadingState.style.display = 'none';
  elements.emptyState.style.display = 'none';
  elements.projectsGrid.style.display = 'grid';
}

/**
 * 添加项目
 */
async function handleAddProject() {
  const name = elements.projectNameInput.value.trim();
  
  if (!name) {
    showToast('请输入项目名称', 'warning');
    elements.projectNameInput.focus();
    return;
  }
  
  // 检查重名
  if (projects.some(p => p.name === name)) {
    showToast('项目名称已存在', 'warning');
    elements.projectNameInput.focus();
    return;
  }
  
  try {
    elements.confirmAddProject.disabled = true;
    
    const response = await api.createProject(name);
    
    if (response.success) {
      showToast(response.message || '项目创建成功', 'success');
      closeModal('addProjectModal');
      await loadProjects();
    } else {
      throw new Error(response.error || '创建项目失败');
    }
  } catch (error) {
    console.error('[Main] 创建项目失败:', error);
    showToast('创建项目失败: ' + error.message, 'error');
  } finally {
    elements.confirmAddProject.disabled = false;
  }
}

/**
 * 重命名项目
 */
async function handleRenameProject() {
  if (!currentProject) return;
  
  const newName = elements.newProjectNameInput.value.trim();
  
  if (!newName) {
    showToast('请输入新的项目名称', 'warning');
    elements.newProjectNameInput.focus();
    return;
  }
  
  if (newName === currentProject.name) {
    closeModal('renameProjectModal');
    return;
  }
  
  // 检查重名
  if (projects.some(p => p.id !== currentProject.id && p.name === newName)) {
    showToast('项目名称已存在', 'warning');
    elements.newProjectNameInput.focus();
    return;
  }
  
  try {
    elements.confirmRenameProject.disabled = true;
    
    const response = await api.renameProject(currentProject.id, newName);
    
    if (response.success) {
      showToast(response.message || '项目重命名成功', 'success');
      closeModal('renameProjectModal');
      await loadProjects();
    } else {
      throw new Error(response.error || '重命名项目失败');
    }
  } catch (error) {
    console.error('[Main] 重命名项目失败:', error);
    showToast('重命名项目失败: ' + error.message, 'error');
  } finally {
    elements.confirmRenameProject.disabled = false;
  }
}

/**
 * 删除项目
 */
async function handleDeleteProject() {
  if (!currentProject) return;
  
  try {
    elements.confirmDeleteProject.disabled = true;
    
    const response = await api.deleteProject(currentProject.id);
    
    if (response.success) {
      showToast(response.message || '项目删除成功', 'success');
      closeModal('deleteConfirmModal');
      await loadProjects();
    } else {
      throw new Error(response.error || '删除项目失败');
    }
  } catch (error) {
    console.error('[Main] 删除项目失败:', error);
    showToast('删除项目失败: ' + error.message, 'error');
  } finally {
    elements.confirmDeleteProject.disabled = false;
  }
}

/**
 * 刷新数据
 */
async function handleRefresh() {
  elements.refreshBtn.disabled = true;
  elements.refreshBtn.querySelector('i').classList.add('fa-spin');
  
  try {
    await loadProjects();
    showToast('数据刷新成功', 'success');
  } catch (error) {
    // 错误已在loadProjects中处理
  } finally {
    elements.refreshBtn.disabled = false;
    elements.refreshBtn.querySelector('i').classList.remove('fa-spin');
  }
}

/**
 * 停用所有环境
 */
async function handleDeactivateAll() {
  const activeProjects = projects.filter(p => p.activeEnvironment);
  
  if (activeProjects.length === 0) {
    showToast('没有激活的环境需要停用', 'info');
    return;
  }
  
  const confirmed = await confirm(`确定要停用所有 ${activeProjects.length} 个激活的环境吗？`);
  if (!confirmed) return;
  
  try {
    elements.deactivateAllBtn.disabled = true;
    
    let successCount = 0;
    const errors = [];
    
    for (const project of activeProjects) {
      try {
        const response = await api.deactivateEnvironment(project.id);
        if (response.success) {
          successCount++;
        } else {
          errors.push(`${project.name}: ${response.error}`);
        }
      } catch (error) {
        errors.push(`${project.name}: ${error.message}`);
      }
    }
    
    if (errors.length === 0) {
      showToast(`成功停用 ${successCount} 个环境`, 'success');
    } else {
      showToast(`停用了 ${successCount} 个环境，${errors.length} 个失败`, 'warning');
      console.error('[Main] 停用环境错误:', errors);
    }
    
    await loadProjects();
  } catch (error) {
    console.error('[Main] 批量停用失败:', error);
    showToast('批量停用失败: ' + error.message, 'error');
  } finally {
    elements.deactivateAllBtn.disabled = false;
  }
}

/**
 * 查看当前规则
 */
async function handleViewRules() {
  try {
    const response = await api.getActiveEnvironments();
    
    if (response.success) {
      const activeEnvironments = response.data || [];
      renderRulesModal(activeEnvironments);
      showModal('viewRulesModal');
    } else {
      throw new Error(response.error || '获取规则失败');
    }
  } catch (error) {
    console.error('[Main] 获取规则失败:', error);
    showToast('获取规则失败: ' + error.message, 'error');
  }
}

/**
 * 渲染规则模态框
 */
function renderRulesModal(activeEnvironments) {
  if (activeEnvironments.length === 0) {
    elements.rulesContainer.innerHTML = `
      <div class="empty-state">
        <i class="fas fa-inbox"></i>
        <h3>暂无激活的规则</h3>
        <p>当前没有任何项目环境处于激活状态</p>
      </div>
    `;
    return;
  }
  
  const html = activeEnvironments.map(env => {
    const project = projects.find(p => p.id === env.projectId);
    if (!project) return '';
    
    let config = '';
    let envName = '';
    
    if (env.environment === 'test') {
      config = project.environments.test;
      envName = '测试环境';
    } else if (env.environment === 'production') {
      config = project.environments.production;
      envName = '生产环境';
    } else if (env.environment.startsWith('custom:')) {
      const ruleId = env.environment.substring(7);
      const rule = project.customRules.find(r => r.id === ruleId);
      if (rule) {
        config = rule.value;
        envName = `自定义规则: ${rule.label}`;
      }
    }
    
    return `
      <div class="rules-section">
        <div class="rules-section-title">
          <i class="fas fa-project-diagram"></i>
          ${escapeHtml(project.name)} - ${escapeHtml(envName)}
        </div>
        <div class="rules-content">${escapeHtml(config || '(空配置)')}</div>
      </div>
    `;
  }).filter(Boolean).join('');
  
  elements.rulesContainer.innerHTML = html;
}

/**
 * 排序处理
 */
function handleSort() {
  renderProjects();
}

/**
 * 键盘快捷键
 */
function handleKeyboard(e) {
  // Ctrl/Cmd + R: 刷新
  if ((e.ctrlKey || e.metaKey) && e.key === 'r') {
    e.preventDefault();
    handleRefresh();
  }
  
  // Ctrl/Cmd + N: 新建项目
  if ((e.ctrlKey || e.metaKey) && e.key === 'n') {
    e.preventDefault();
    showModal('addProjectModal');
  }
  
  // ESC: 关闭模态框
  if (e.key === 'Escape') {
    const openModal = document.querySelector('.modal.show');
    if (openModal) {
      closeModal(openModal.id);
    }
  }
}

/**
 * 启动自动刷新
 */
function startAutoRefresh() {
  // 每30秒自动刷新一次统计信息
  setInterval(async () => {
    if (!isLoading) {
      try {
        const response = await api.getStats();
        if (response.success) {
          updateStats();
        }
      } catch (error) {
        // 静默失败，不显示错误
        console.warn('[Main] 自动刷新统计失败:', error);
      }
    }
  }, 30000);
}

// === 项目操作函数（供HTML调用） ===

/**
 * 编辑项目
 */
window.editProject = function(projectId) {
  const project = projects.find(p => p.id === projectId);
  if (!project) return;
  
  // 跳转到详细配置页
  window.location.href = `config.html?project=${projectId}`;
};

/**
 * 切换环境
 */
window.toggleEnvironment = async function(projectId, environment) {
  const project = projects.find(p => p.id === projectId);
  if (!project) return;
  
  // 检查API客户端是否已初始化
  if (!checkApiReady()) {
    return;
  }
  
  try {
    if (project.activeEnvironment === environment) {
      // 如果当前环境已激活，则停用
      console.log('[Main] 停用环境:', projectId, environment);
      const response = await api.deactivateEnvironment(projectId);
      console.log('[Main] 停用环境响应:', response);
      if (response.success) {
        showToast(response.message, 'success');
        await loadProjects();
      } else {
        showToast(response.error || '停用失败', 'error');
        await loadProjects(); // 即使失败也要刷新界面
      }
    } else {
      // 激活环境
      console.log('[Main] 激活环境:', projectId, environment);
      const response = await api.activateEnvironment(projectId, environment);
      console.log('[Main] 激活环境响应:', response);
      if (response.success) {
        showToast(response.message, 'success');
        await loadProjects();
      } else {
        showToast(response.error || '激活失败', 'error');
        await loadProjects(); // 即使失败也要刷新界面
      }
    }
  } catch (error) {
    console.error('[Main] 切换环境失败:', error);
    showToast('操作失败: ' + error.message, 'error');
    await loadProjects(); // 即使出现异常也要刷新界面
  }
};

/**
 * 切换自定义规则
 */
window.toggleCustomRule = async function(projectId, ruleId) {
  const project = projects.find(p => p.id === projectId);
  if (!project) return;
  
  try {
    const environment = `custom:${ruleId}`;
    
    if (project.activeEnvironment === environment) {
      // 如果当前规则已激活，则停用
      const response = await api.deactivateEnvironment(projectId);
      if (response.success) {
        showToast(response.message, 'success');
        await loadProjects();
      }
    } else {
      // 激活自定义规则
      const response = await api.activateCustomRule(projectId, ruleId);
      if (response.success) {
        showToast(response.message, 'success');
        await loadProjects();
      }
    }
  } catch (error) {
    console.error('[Main] 切换自定义规则失败:', error);
    showToast('操作失败: ' + error.message, 'error');
  }
};

/**
 * 停用项目
 */
window.deactivateProject = async function(projectId) {
  const project = projects.find(p => p.id === projectId);
  if (!project) return;
  
  try {
    const response = await api.deactivateEnvironment(projectId);
    if (response.success) {
      showToast(response.message, 'success');
      await loadProjects();
    }
  } catch (error) {
    console.error('[Main] 停用项目失败:', error);
    showToast('操作失败: ' + error.message, 'error');
  }
};

/**
 * 显示项目菜单
 */
window.showProjectMenu = function(projectId, event) {
  const project = projects.find(p => p.id === projectId);
  if (!project) return;
  
  event.stopPropagation();
  
  // 简单的右键菜单实现
  currentProject = project;
  
  const menu = document.createElement('div');
  menu.className = 'context-menu';
  menu.style.cssText = `
    position: fixed;
    top: ${event.clientY}px;
    left: ${event.clientX}px;
    background: white;
    border: 1px solid var(--gray-300);
    border-radius: var(--radius-md);
    box-shadow: var(--shadow-lg);
    z-index: 1000;
    padding: var(--spacing-xs);
    min-width: 150px;
  `;
  
  menu.innerHTML = `
    <div style="padding: var(--spacing-sm) var(--spacing-md); cursor: pointer; border-radius: var(--radius-sm);" 
         onmouseover="this.style.background='var(--gray-100)'" 
         onmouseout="this.style.background=''" 
         onclick="renameProject('${project.id}')">
      <i class="fas fa-edit"></i> 重命名
    </div>
    <div style="padding: var(--spacing-sm) var(--spacing-md); cursor: pointer; border-radius: var(--radius-sm);" 
         onmouseover="this.style.background='var(--gray-100)'" 
         onmouseout="this.style.background=''" 
         onclick="editProject('${project.id}')">
      <i class="fas fa-cog"></i> 配置
    </div>
    <hr style="margin: var(--spacing-xs) 0; border: none; border-top: 1px solid var(--gray-200);">
    <div style="padding: var(--spacing-sm) var(--spacing-md); cursor: pointer; color: var(--danger-color); border-radius: var(--radius-sm);" 
         onmouseover="this.style.background='var(--gray-100)'" 
         onmouseout="this.style.background=''" 
         onclick="deleteProject('${project.id}')">
      <i class="fas fa-trash"></i> 删除
    </div>
  `;
  
  document.body.appendChild(menu);
  
  // 点击其他地方关闭菜单
  const closeMenu = (e) => {
    if (!menu.contains(e.target)) {
      menu.remove();
      document.removeEventListener('click', closeMenu);
    }
  };
  
  setTimeout(() => {
    document.addEventListener('click', closeMenu);
  }, 0);
};

/**
 * 重命名项目
 */
window.renameProject = function(projectId) {
  const project = projects.find(p => p.id === projectId);
  if (!project) return;
  
  currentProject = project;
  elements.newProjectNameInput.value = project.name;
  showModal('renameProjectModal');
  
  // 关闭菜单
  const menu = document.querySelector('.context-menu');
  if (menu) menu.remove();
};

/**
 * 删除项目
 */
window.deleteProject = function(projectId) {
  const project = projects.find(p => p.id === projectId);
  if (!project) return;
  
  currentProject = project;
  elements.deleteProjectName.textContent = project.name;
  showModal('deleteConfirmModal');
  
  // 关闭菜单
  const menu = document.querySelector('.context-menu');
  if (menu) menu.remove();
};

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', initApp);